import { Component, OnInit } from '@angular/core';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
import { ProductDto } from '../../../proxy/storage';
import { CommonModule } from '@angular/common';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { CheckboxModule } from 'primeng/checkbox';

@Component({
  selector: 'app-product-select-modal',
  standalone: true,
  imports: [
    CommonModule,
    TableModule,
    ButtonModule,
    CheckboxModule
  ],
  template: `
    <div class="p-fluid">
      <div class="p-field">
        <p-table
          [value]="products"
          selectionMode="multiple"
          [(selection)]="selectedProducts"
          dataKey="id"
          [scrollable]="true"
          scrollHeight="400px"
        >
          <ng-template pTemplate="header">
            <tr>
              <th style="width: 3rem">
                <p-tableHeaderCheckbox></p-tableHeaderCheckbox>
              </th>
              <th>产品编码</th>
              <th>产品名称</th>
              <th>型号</th>
              <th>单位</th>
              <th>库存数量</th>
            </tr>
          </ng-template>
          <ng-template pTemplate="body" let-product>
            <tr [pSelectableRow]="product">
              <td>
                <p-tableCheckbox [value]="product"></p-tableCheckbox>
              </td>
              <td>{{ product.productCode }}</td>
              <td>{{ product.productName }}</td>
              <td>{{ product.model }}</td>
              <td>{{ product.unit }}</td>
              <td>{{ product.quantityOnHand }}</td>
            </tr>
          </ng-template>
        </p-table>
      </div>
      <div class="p-dialog-footer">
        <button pButton type="button" label="确定" (click)="confirm()"></button>
        <button pButton type="button" label="取消" (click)="close()" class="p-button-secondary"></button>
      </div>
    </div>
  `,
  styleUrls: ['./product-select-modal.component.scss']
})
export class ProductSelectModalComponent implements OnInit {
  products: ProductDto[] = [];
  selectedProducts: ProductDto[] = [];

  constructor(
    public ref: DynamicDialogRef,
    public config: DynamicDialogConfig
  ) {}

  ngOnInit() {
    // 这里应该从服务获取产品列表
    // 暂时使用模拟数据
    this.products = [
      {
        id: '12345678-1234-5678-1234-567812345678',  // 使用有效的GUID格式
        productCode: 'P001',
        productName: '测试产品1',
        productType: '类型1',
        model: 'M001',
        unit: '个',
        quantityOnHand: 100
      },
      {
        id: '87654321-4321-8765-4321-876543210987',  // 使用有效的GUID格式
        productCode: 'P002',
        productName: '测试产品2',
        productType: '类型2',
        model: 'M002',
        unit: '个',
        quantityOnHand: 200
      }
    ];
  }

  confirm() {
    this.ref.close(this.selectedProducts);
  }

  close() {
    this.ref.close();
  }
}